package edu.tgc.security;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

import edu.tgc.entity.system.SysUser;
import edu.tgc.service.system.SysUserService;

public class SysUserDetailsService implements UserDetailsService {

    protected final Log logger = LogFactory.getLog(getClass());
    protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
    @Autowired
    protected PasswordEncoder passwordEncoder;
    @Autowired
    protected SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = this.sysUserService.getByUsername(username);
        if (sysUser != null) {
            return new SessionUser(sysUser, this.sysUserService.getAuthorities(sysUser));
        }
        throw new UsernameNotFoundException(this.messages.getMessage("JdbcDaoImpl.notFound", new Object[] { username }, "Username {0} not found"));
    }

    public void setMessageSource(MessageSource messageSource) {
        this.messages = new MessageSourceAccessor(messageSource);
    }

}
